<template>
  <q-page class="q-pa-md wrapBox">
    <div v-loading="loading">
      <div class="nav">
        <el-breadcrumb separator="/">
          <el-image src="/svgs/algManagementIcon.svg" style="width: 17px;margin: 0 10px 0 0" fit />
          <el-breadcrumb-item>{{ $t('algorithmServices') }}</el-breadcrumb-item>
          <el-breadcrumb-item><span style=" color: #333;">{{ $t('algorithmManagement') }}</span></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="datasetBox" style="position: relative">
        <div class="contentBox_title">
          <span>{{ $t('algorithmManagement') }}</span>
          <el-image src="/svgs/algManageDocumentIcon.svg" style="width: 12px" class="icon" fit />
          <span class="text">{{ $t('viewAlgorithmSpecifications') }}</span>
        </div>
        <div class="contentBox">
          <div class="searchWrap" style="margin-top: 10px">
            <div>
              <el-input v-model.trim="searchName" placeholder="搜索算法名称" spellcheck="false" @keyup.enter="filterDataset">
                <template #prepend>
                  <el-select v-model="typeValue" placeholder="全部" style="width: 150px;background-color: #fff">
                    <el-option v-for="item in AlgorithmSource" :key="item.value" :label="item.label" :value="item.value"
                      @click="filterDataset" />
                  </el-select>
                </template>
                <template #append>
                  <el-button :icon="Search" @click="filterDataset" />
                </template>
              </el-input>
            </div>
            <div>
              <el-button type="primary" size="default" @click="toCreatePage">{{ $t('newBuilt') }}</el-button>
            </div>
          </div>
          <el-table
            style="margin-top: 15px"
            :data="labelAssignData.results" stripe
            :header-cell-style="{
               background: '#f9f9f9',
               color: '#333',
               fontWeight: '500',
               fontSize: '14px',
               textAlign: 'left',
               height: '56px'
            }"
          >
            <el-table-column align="left" prop="title" label="名称" width="150">
              <template #default="scope">
                <el-button link type="primary" @click="toDetailPage(scope.row.id)">{{ scope.row.title }}</el-button>
              </template>
            </el-table-column>
            <el-table-column align="left" prop="type" label="标签" width="80" />
            <el-table-column align="left" prop="git_version" label="版本" width="140" />
            <el-table-column align="left" prop="git_vendor" label="仓库类型" width="120" />
            <el-table-column align="left" prop="git_uri" label="来源" width="160">
              <template #default="scope">
                <div class="overflowText" :title="scope.row.git_uri">
                  {{ scope.row.git_uri }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" prop="description" label="描述" width="150">
              <template #default="scope">
                <div class="overflowText" :title="scope.row.description">
                  {{ scope.row.description ? scope.row.description : '-' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" prop="create_at" label="创建时间" width="180" />
            <el-table-column align="left" prop="labels" label="操作">
              <template #default="scope">
                <el-button v-show="userStatus ? true : scope.row.creator_username == userInfoName" link type="primary"
                  size="small" @click="toCreateModelManage(scope.row.id)">创建训练作业</el-button>
                <el-button v-show="showPublicMarket(scope.row)&&!scope.row.is_public&&!scope.row.is_subscription" link type="primary"
                  size="small" @click="deleteFun(scope.row.id)">删除</el-button>
                <el-button v-show="showPublicMarket(scope.row)&&!scope.row.is_public&&scope.row.is_subscription==false" link type="primary" size="small"
                  @click="publicMarketFun(scope.row.id)">发布公开市场</el-button>
                <el-button v-show="showPublicMarket(scope.row)&&scope.row.is_public&&scope.row.is_subscription==false" link type="primary" size="small"
                  @click="unPublicMarketFun(scope.row.id)">下架公开市场</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="row" style="justify-content: end;margin-top: 10px;background-color: #fff;padding: 10px 0 "
          v-if="labelAssignData.results.length > 0">
          <el-pagination background layout="total, prev, pager, next, sizes, jumper" :page-sizes="[10, 20, 50]"
            :total="labelAssignData.count" v-model:current-page="pageData.page"
            v-model:page-size="pageData.page_size" :current-page="pageData.page" @size-change="sizeChange"
            @current-change="changePage" />
        </div>
      </div>
      <q-dialog v-model="dialogDeleteData">
        <q-card style="width: 450px;">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px;">
              <el-icon style="
                  color: #FFA940;
                  display: inline-block;
                  vertical-align: middle;
                  margin-top: -3px;
                  font-size: 25px;
                ">
                <WarningFilled />
              </el-icon>
              <span style="font-size: 16px;margin-left: 5px; color: #FFA940;">删除提醒</span>
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none" style="padding-left: 45px">
            <div>确定删除本算法吗？删除后不可恢复，请谨慎操作！</div>
          </q-card-section>
          <q-card-actions align="right" class="text-primary" style="margin-right: 20px;margin-top: 10px">
            <el-button @click="deleteData" style="background-color: #fff">确认删除</el-button>
            <el-button type="primary" v-close-popup>放弃删除</el-button>
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
  </q-page>
</template>


<script setup lang="ts">

import { reactive, ref, computed } from "vue";
import { useRouter } from 'vue-router';
import { getModelList, deleteAlgData } from 'src/api/model'
import { publicMarket, unPublicMarket } from 'src/api/market'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { modelStore } from 'src/stores/model';
import { Search } from '@element-plus/icons-vue'
import { AlgorithmSource } from 'src/utils/useData';
import {dataSetStore} from "stores/dataSet";
const router = useRouter()
const typeValue = ref('');
const projectId = router.currentRoute.value.params.project_id
const dataId = ref()
const loading = ref(false)
const searchName = ref('')
const dialogDeleteData = ref(false)
const pageData = dataSetStore().pageData;
const userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;//判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username')//获取用户登录的用户名
let labelAssignData = reactive(
  {
    count: 0,
    next: "",
    previous: "",
    results: []
  }
)
const showPublicMarket = ((rowData: any) => {
  let state = userStatus ? true : rowData.creator_username == userInfoName
  let showMarketBtn = false
  if (state && JSON.parse(localStorage.user).is_admin) {
    showMarketBtn=true
  }

  return showMarketBtn
})


function toDetailPage(data_id: number) {
  const dataSetObj = modelStore()
  dataSetObj.dataset(data_id)
  router.push({ name: 'alg-manage-detail', params: { project_id: projectId } })
}
function filterDataset() {
  dataSetStore().setPageData(1);
  getDataList();
}
getDataList()
function getDataList() {
  loading.value = true;
  let obj: any = {}
  if (typeValue.value != '') obj.git_vendor = typeValue.value;
  if (searchName.value != '') obj.title = searchName.value;
  obj = Object.assign(obj, pageData);
  getModelList(projectId, obj).then((res: any) => {
    labelAssignData = res.data
  }).finally(() => {
    loading.value = false
  })
}

function sizeChange(pageSize: any) {
  dataSetStore().setPageData(1);
  dataSetStore().setPageSizeData(pageSize);
  getDataList();
}

function changePage(currentPage: any) {
  dataSetStore().setPageData(currentPage);
  getDataList()
}
function toCreatePage() {
  router.push({ name: 'alg-manage-create', params: { project_id: projectId } })
}

function deleteFun(id: number) {
  dialogDeleteData.value = true
  dataId.value = id
}
function deleteData() {
  dialogDeleteData.value = false
  deleteAlgData(projectId, dataId.value).then((res: any) => {
    loading.value = true
    ElNotification({
      title: 'Success',
      message: '删除成功',
      type: 'success',
    })
  }).finally(() => {
    getDataList()
  }).catch((error) => {
    ElMessageBox.alert('当前算法下有正在进行中的训练任务', '错误提示', {
      confirmButtonText: '知道了',
    })
    // console.log(error.response)
  })
}
function toCreateModelManage(id: number) {
  const dataSetObj = modelStore()
  dataSetObj.dataset(id)
  router.push({ name: 'model-manage-create', params: { project_id: projectId } })
}
// 发布公开市场
function publicMarketFun(id: number) {
  ElMessageBox.confirm('确定发布到公开市场吗?', '发布公开市场', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    publicMarket(projectId, id).then(() => {
      ElMessage.success('发布公开市场成功')
      getDataList()
    }).catch((error) => {
      console.log(error)
    })
  })
}
// 下架公开市场
function unPublicMarketFun(id: number) {
  ElMessageBox.confirm('确定在公开市场下架吗?', '下架公开市场', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    unPublicMarket(projectId, id).then(() => {
      ElMessage.success('下架公开市场成功')
      getDataList()
    }).catch((error) => {
      console.log(error)
    })
  })
}
</script>

<style scoped lang="scss">
.wrapBox {
  padding: 0 !important;
  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: var(--nav-bg-color);
    height: 46px;

    ::v-deep .el-breadcrumb {
      display: flex;
      align-items: center;
    }
  }
  .datasetBox {
    margin: 0 20px;
    .contentBox_title{
      position: relative;
      display: flex;
      align-items: center;
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
      .icon{
        //position: absolute;
        //left: 90px;
        //top: 22px;
        margin-left: 10px;
        margin-top: 14px;
        width: 17px;
      }
      .text{
        //position: absolute;
        //left: 104px;
        //top: 19px;
        margin-left: 10px;
        font-size: 12px;
        color: #3d5ce4;
        font-weight: 400;
        cursor: pointer;
      }
    }

    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
      .searchWrap{
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
//点击下拉框，去掉输入框蓝色高亮显示
:deep(.el-input){
  --el-input-focus-border:#fff;
  --el-input-transparent-border: 0 0 0 0px;
  --el-input-border-color:var(--el-border-color);
  --el-input-hover-border:0px !important;
  --el-input-hover-border-color:var(--el-border-color);
  --el-input-focus-border-color:var(--el-border-color);
  --el-input-clear-hover-color:var(--el-border-color);
}

.overflowText{
  text-overflow: ellipsis;
  overflow: hidden;
  width: 140px;
  white-space: nowrap;
  cursor: pointer
}
//分页前往 start
::v-deep .el-pagination__goto {
  margin-left: 20px;
}
//end
//分页输入框跳转不限制
::v-deep disabled,::v-deep  .disabled *, ::v-deep [disabled],::v-deep [disabled] * {
  outline: 10px !important;
  cursor: pointer !important;
}
</style>
